"""数据库模型定义（简化版）
只保留核心功能的数据模型
"""
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Optional, Dict, Any
import json

@dataclass
class StockFearGreed:
    """股票恐贪数据模型"""
    symbol: str
    date: date
    open_price: str
    high_price: str
    low_price: str
    close_price: str
    volume: str
    fear_greed_index: str = '50.000'
    sentiment: str = '中性'
    investment_advice: str = '持有'
    rsi: str = '50.000'
    volatility: str = '0.000'
    volume_ratio: str = '1.000'
    put_call_ratio: str = '1.000'
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        return {
            'symbol': self.symbol,
            'date': self.date.strftime('%Y-%m-%d'),
            'open_price': float(self.open_price) if self.open_price != '0.0' else 0.0,
            'high_price': float(self.high_price) if self.high_price != '0.0' else 0.0,
            'low_price': float(self.low_price) if self.low_price != '0.0' else 0.0,
            'close_price': float(self.close_price) if self.close_price != '0.0' else 0.0,
            'volume': int(float(self.volume)) if self.volume != '0' else 0,
            'fear_greed_index': float(self.fear_greed_index) if self.fear_greed_index not in ['50.000', '0.000'] else (0.0 if self.fear_greed_index == '0.000' else 50.0),
            'sentiment': self.sentiment,
            'investment_advice': self.investment_advice,
            'rsi': float(self.rsi) if self.rsi != '50.000' else 50.0,
            'volatility': float(self.volatility) if self.volatility != '0.000' else 0.0,
            'volume_ratio': float(self.volume_ratio) if self.volume_ratio != '1.000' else 1.0,
            'put_call_ratio': float(self.put_call_ratio) if self.put_call_ratio != '1.000' else 1.0
        }

    def to_dataframe_format(self) -> Dict[str, Any]:
        """转换为DataFrame格式 (for raw data)"""
        return {
            'Open': float(self.open_price),
            'High': float(self.high_price),
            'Low': float(self.low_price),
            'Close': float(self.close_price),
            'Volume': int(self.volume)
        }

@dataclass
class StockKline:
    """股票K线数据模型（纯粹的服务器数据）"""
    symbol: str
    date: date
    open_price: str
    high_price: str
    low_price: str
    close_price: str
    volume: str
    data_source: str = 'akshare'
    market_type: str = 'US'
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        return {
            'symbol': self.symbol,
            'date': self.date.strftime('%Y-%m-%d'),
            'open_price': float(self.open_price) if self.open_price != '0.0' else 0.0,
            'high_price': float(self.high_price) if self.high_price != '0.0' else 0.0,
            'low_price': float(self.low_price) if self.low_price != '0.0' else 0.0,
            'close_price': float(self.close_price) if self.close_price != '0.0' else 0.0,
            'volume': int(float(self.volume)) if self.volume != '0' else 0,
            'data_source': self.data_source,
            'market_type': self.market_type
        }

    def to_dataframe_format(self) -> Dict[str, Any]:
        """转换为DataFrame格式"""
        return {
            'Open': float(self.open_price),
            'High': float(self.high_price),
            'Low': float(self.low_price),
            'Close': float(self.close_price),
            'Volume': int(self.volume)
        }

@dataclass
class StockProphecyModel:
    """股票预测模型结果模型"""
    symbol: str
    date: date
    model_type: str
    prediction: str
    confidence: str = '0.000'
    features_count: int = 0
    model_accuracy: str = '0.000'
    training_date: Optional[date] = None
    feature_importance: Optional[str] = None
    macro_indicators: Optional[str] = None
    id: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        result = {
            'symbol': self.symbol,
            'date': self.date.strftime('%Y-%m-%d'),
            'model_type': self.model_type,
            'prediction': self.prediction,
            'confidence': float(self.confidence) if self.confidence != '0.000' else 0.0,
            'features_count': self.features_count,
            'model_accuracy': float(self.model_accuracy) if self.model_accuracy != '0.000' else 0.0
        }
        
        if self.training_date:
            result['training_date'] = self.training_date.strftime('%Y-%m-%d')
        
        if self.feature_importance:
            try:
                result['feature_importance'] = json.loads(self.feature_importance)
            except:
                result['feature_importance'] = {}
        
        if self.macro_indicators:
            try:
                result['macro_indicators'] = json.loads(self.macro_indicators)
            except:
                result['macro_indicators'] = {}
        
        return result

@dataclass
class StockBasicInfo:
    """股票基础信息模型"""
    symbol: str
    name: str
    market_type: str
    sector: str = ''
    industry: str = ''
    country: str = ''
    currency: str = 'USD'
    exchange: str = ''
    is_active: str = 'Y'
    custom_category: str = ''
    description: Optional[str] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    def to_api_format(self) -> Dict[str, Any]:
        """转换为API格式"""
        return {
            'symbol': self.symbol,
            'name': self.name,
            'market_type': self.market_type,
            'sector': self.sector,
            'industry': self.industry,
            'country': self.country,
            'currency': self.currency,
            'exchange': self.exchange,
            'is_active': self.is_active == 'Y',
            'custom_category': self.custom_category,
            'description': self.description
        }
